% Read DICOM image files and save them as a sequence of images
function DicomImport();


%DEBUG%
% PathName = 'S:\02211632\'
% SaveName = 'C:\Documents and Settings\conrabp\My Documents\Research\Banks\HannesFluoro\OSMI'

startPath = 'C:\';
PathName = uigetdir(startPath, 'Select folder containing DICOM files');
FileList = dir(PathName);
firstfileFlag = 0;
fileCount = 0;

for i = 1:length(FileList)
    if ~strncmpi(FileList(i).name, '.', 1)
        imageName = fullfile(PathName,FileList(i).name);
        I = dicomread(imageName);
        info = dicominfo(imageName);
        fileCount = fileCount + 1;
        disp(['Processing sequence ' num2str(fileCount)]);
        if firstfileFlag == 0;
            SaveName = uigetdir(PathName, 'Select parent folder to save image sequence');
            patientPath = fullfile(SaveName,info.StudyDate);
            mkdir(patientPath);
            firstfileFlag = 1;
        end
        try, 
            dummy = info.StopTrim;
            mkdir(fullfile(patientPath,['Trial' num2str(fileCount)]));
            for j = 1:info.StopTrim
                num = sprintf('%04g',j);
                disp([' Image ' num ' of ' num2str(info.StopTrim) ' saved']);
                trialPath = fullfile(patientPath,['Trial' num2str(fileCount)], [FileList(i).name '_Trial' num2str(fileCount) '_' num '.tif']);
                imwrite(I(:,:,j), trialPath,'tiff','Description', info.RequestedProcedureDescription, 'Compression', 'none');
            end
        catch,
            disp('Sequence ERROR:')
            err=lasterror;
            disp(err.message)
            try,
                dummy = info.OverlayType_0;
                mkdir(fullfile(patientPath,'Calibration'));
                trialPath = fullfile(patientPath,'Calibration',[FileList(i).name  '_Calibration.tif']);
                imwrite(I(:,:), trialPath,'tiff','Description', info.RequestedProcedureDescription, 'Compression', 'none');
                disp('Calibration image saved');
            catch,
                disp('Single Image ERROR:') 
                err=lasterror;
                disp(err.message)
                continue
            end              
        end
        I = [];
    end
end

        